package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.model.vo.chat.ChatMessageVo;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RecallMessageHandler implements MessageHandler {

    private static ChatMessagesService messageService;
    private static ChatConversationService chatConversationService;

    @Autowired
    public void setService(ChatMessagesService messageService,
                           ChatConversationService chatConversationService) {
        RecallMessageHandler.messageService = messageService;
        RecallMessageHandler.chatConversationService = chatConversationService;
    }

    @Override
    public void handle(Session session, JSONObject message) {
        Long messageId = message.getLong("messageId");
        String userId = WebSocketChatService.getUserId(session);
        ChatMessagesEntity chatMessagesEntity = messageService.getById(messageId);
        // 1. 校验消息归属和撤回权限
        boolean msg = messageService.validateRecallPermission(messageId, userId);
        if (msg) {
            UpdateWrapper<ChatMessagesEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", messageId).
                    set("msg_status", "3");
            updateWrapper.set("post_messages", "撤回了一条消息");
            // 2. 更新消息状态为已撤回
//        msg.setUpdateTime(LocalDateTime.now());
            messageService.update(updateWrapper);
//            // 判断是不是最后一条消息
//            if (chatConversationService.isLastMessage(chatMessagesEntity.getConversationId(), String.valueOf(messageId))) {
//               chatConversationService.updateRecallMessageId(chatMessagesEntity.getConversationId());
//            }

            // 3. 推送撤回通知给相关用户
            pushRecallNotice(chatMessagesEntity.getConversationId(), userId, messageId,"成功");
        } else {
            pushRecallNotice(chatMessagesEntity.getConversationId(), userId, messageId,"无权撤回该消息");
        }
    }

    private void pushRecallNotice(String conversationId, String userId, Long messageId,String msg) {
        ChatConversationEntity entity = chatConversationService.getById(conversationId);
        ChatMessagesEntity messagesEntity = messageService.getById(messageId);

        JSONObject msgFromJson = buildResponseJson(entity.getUser1Id(), messagesEntity);
        JSONObject msgToJson = buildResponseJson(entity.getUser2Id(), messagesEntity);
//        msgJson.put("type", "recall");
//        msgJson.put("messageId", messageId);
//        msgJson.put("userId", userId);
//        msgJson.put("conversationId", conversationId);
//        String formattedTime = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)
//                .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
//        msgJson.put("time", formattedTime);
//        msgJson.put("msg", msg);
        String message2 = msgToJson.toJSONString();
        String message = msgFromJson.toJSONString();
        WebSocketChatService.sendMessageToUserId(entity.getUser1Id(), message);
        WebSocketChatService.sendMessageToUserId(entity.getUser2Id(), message2);
//        if (entity.getUser1Id().equals(userId)) {
//            WebSocketChatService.sendMessageToUserId(entity.getUser2Id(), message);
//        } else {
//            WebSocketChatService.sendMessageToUserId(entity.getUser1Id(), message);
//        }
    }
    private JSONObject buildResponseJson(String userId, ChatMessagesEntity entity) {
        JSONObject resJson = new JSONObject();
        ChatMessageVo vo = messageService.convertToDTO(entity);
        vo.setSender(entity.getFormUserId().equals(userId));
        resJson.put("type", "recall");
        resJson.put("message", vo);
        resJson.put("conversationId", entity.getConversationId());
        return resJson;
    }

}
